const router = require('express').Router()
const _ = require('lodash/fp')
const U = require('../../utils')
const Shop = require('../../models/shop')


function abort_invalid_input(req,res,next){
  const shop = req.body.shop
  const pass = req.body.pass

  if(shop == null || pass == null){
    res.json(U.Err('请提供用户名和密码'))
    return
  }

  next()
}

function abort_shop_not_exsit(req,res,next){
  const shop = req.body.shop
  const pass = req.body.pass

  const correct_shop = Shop.get_by_shop(shop)

  if(correct_shop == null){
    res.json(U.Err('不存在该店家'))
    return
  }

  req.correct_shop = correct_shop

  next()
}

function check_pass(req,res,next){
  if(req.body.pass != req.correct_shop.pass){
    res.json(U.Err('密码不正确'))
    return
  }
  next()
}


router.post('/login',abort_invalid_input, abort_shop_not_exsit, check_pass, (req,res) => {
  req.session.shop = req.correct_shop
  res.json(U.Ok('登陆成功'))
})

module.exports = router